<template>
	<div class="app-control-form__mdctrl">
		<template v-if="contentType == 'LIST'">
			<slot
				:viewParams="viewParams"
				:context="context"
				:handleCtrlInit="handleCtrlInit"
				:handleCtrlAction="handleCtrlAction"
				:handleCtrlDestroy="handleCtrlDestroy"
			></slot>
		</template>
		<template v-else>
			<AppButton
				type="primary"
				class="repeater-add"
				size="small"
				shape="round"
				@click="add"
			>
				<template #icon>
					<van-icon name="plus" />
				</template>
			</AppButton>
			<van-swipe-cell
				class="app-control-form__mdctrl__item"
				v-for="(item, index) in items"
				:key="item.data[deKeyField.toLowerCase()]"
			>
				<slot
					:viewParams="viewParams"
					:context="item.context"
					:handleCtrlInit="
						(name: string, ability: any) => handleCtrlInit(name, ability, item)
					"
					:handleCtrlAction="handleCtrlAction"
					:handleCtrlDestroy="handleCtrlDestroy"
				></slot>

				<template #right>
					<van-button square type="danger" text="删除" @click="remove(index)" />
				</template>
			</van-swipe-cell>
		</template>
	</div>
</template>
<script setup lang="ts">
import { IEvent, IParam, deepCopy, createUUID } from '@/core';
import { formMDCtrlProps } from '../form';
const props = defineProps(formMDCtrlProps);
interface ComponentEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const emit = defineEmits<ComponentEmit>();

let childFormCount: number = 0;

let errorInfoCount: number = 0;

let items = ref<IParam[]>([]);

let dataService: any = null;

let ability: any = null;

const handleCtrlInit = (name: string, _ability: any, item?: IParam) => {
	if (Object.is(props.contentType, 'FORM') && item) {
		item.ability = _ability;
		return;
	}
};

const handleCtrlAction = (name: string, action: string, data: IParam[]) => {
	if (Object.is(action, 'save')) {
		if (Object.is(props.contentType, 'FORM')) {
			childFormCount++;
			if (childFormCount === items.value.length) {
				mdCtrlDataSaved();
			}
		} else {
			mdCtrlDataSaved();
		}
	}
};

const handleCtrlDestroy = (name: string, data: IParam) => {};

const handleRequestContext = () => {
	let tempContext = deepCopy(props.context);
	if (tempContext && tempContext.srfsessionid) {
		tempContext.srfsessionkey = tempContext.srfsessionid;
		delete tempContext.srfsessionid;
	}
	return tempContext;
};

const loadData = async () => {
	items.value = [];
	if (
		Object.is(props.contentType, 'FORM') &&
		dataService &&
		dataService['FetchTempDefault'] &&
		dataService['FetchTempDefault'] instanceof Function
	) {
		const context = handleRequestContext();
		const response = await dataService['FetchTempDefault'](
			context,
			props.viewParams
		);
		if (response.success) {
			handleData(response.data);
		}
	}
};

const handleData = (data: IParam[]) => {
	data.forEach((_item: IParam) => {
		const context = deepCopy(props.context);
		Object.assign(context, {
			[props.entityCodeName.toLowerCase()]:
				_item[props.deKeyField.toLowerCase()],
		});
		items.value.push({ context, data: _item });
	});
};

const add = async () => {
	if (
		dataService &&
		props.deKeyField &&
		dataService['CreateTemp'] &&
		dataService['CreateTemp'] instanceof Function
	) {
		const data = { [props.deKeyField.toLowerCase()]: createUUID() };
		const context = handleRequestContext();
		const response = await dataService['CreateTemp'](context, data);
		if (response.success) {
			handleData([response.data]);
		}
	}
};

const remove = async (index: number) => {
	if (
		dataService &&
		dataService['RemoveTemp'] &&
		dataService['RemoveTemp'] instanceof Function
	) {
		const context = handleRequestContext();
		const item = items.value[index];
		const response = await dataService['RemoveTemp'](context, item.data);
		if (response.success) {
			items.value.splice(index, 1);
		}
	}
};

const initMDCtrl = async () => {
	dataService = await App.getDataService(props.entityCodeName, props.context);
	const executeFormDetail = ({ name, action, data }: IEvent<string>) => {
		switch (action) {
			case 'load':
				loadData();
				break;
			case 'beforeSave':
				mdCtrlBeforeSave();
				break;
			case 'save':
				loadData();
				break;
			case 'add':
				add();
				break;
			case 'remove':
				remove(data);
				break;
		}
	};
	emit('component-action', {
		name: props.name,
		action: 'componentInit',
		data: { executeFormDetail },
	});
};

initMDCtrl();

const mdCtrlDataSaved = () => {
	emit('component-action', {
		name: props.name,
		action: 'mdCtrlDataSave',
		data: { type: 'MDCTRL' },
	});
};

const mdCtrlBeforeSave = () => {
	if (Object.is(props.contentType, 'FORM')) {
		if (items.value.length == 0) {
			mdCtrlDataSaved();
			return;
		} else {
			childFormCount = 0;
			errorInfoCount = 0;
		}
	}
	mdCtrlSave();
};

const mdCtrlSave = () => {
	try {
		if (Object.is(props.contentType, 'FORM')) {
			items.value.forEach((item: IParam) => {
				if (item.ability) {
					item.ability.save({}, false);
				}
			});
		} else {
			if (ability) {
				ability.save({ srfshowinfo: false });
			}
		}
	} catch (error) {}
};
</script>
